package top.codedance.iotp.common.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.LaxRedirectStrategy;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

public class HttpRequestUtil {
    public static JSONObject post(String url, String jsonStr){
        return post(url, jsonStr, -1);
    }

    public static JSONObject post(String url, String jsonStr, int timeout){
        CloseableHttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
        HttpPost httpPost = new HttpPost(url);
        if(jsonStr != null) {
            StringEntity entity = new StringEntity(jsonStr, StandardCharsets.UTF_8);
            httpPost.setEntity(entity);
        }
        httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
        if(timeout > 0) {
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000 * timeout).build();
            httpPost.setConfig(requestConfig);
        }
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            StatusLine statusLine = response.getStatusLine();
            if (responseEntity != null && statusLine.getStatusCode() == 200) {
                BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8));
                StringBuffer sb = new StringBuffer("");
                String line = "";
                while ((line = in.readLine()) != null) {
                    sb.append(line);
                }
                in.close();
                String content = sb.toString();
                return JSONObject.parseObject(content);
            }else{
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("status", 500);
                jsonObject.put("message", "未正常返回");
                return jsonObject;
            }
        } catch (Exception e) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("status", 500);
            jsonObject.put("message", e.getMessage());
            return jsonObject;
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {}
        }
    }
}
